package com.alibaba.algo.components.yapi.handler;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.algo.components.yapi.annotations.ApiModel;
import com.alibaba.algo.components.yapi.entity.Node;
import com.alibaba.algo.components.yapi.util.ClazzUtils;
import com.alibaba.algo.components.yapi.vo.ReqHeaders;
import com.alibaba.algo.components.yapi.vo.RequestHandlerResponseVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JsonRequestHandler implements RequestHandler {

	@Override
	public RequestHandlerResponseVO handler(Method method) {
		Parameter[] params = method.getParameters();
		JSONObject json = new JSONObject();
		// 方法没有参数的情况
		if (params == null || params.length == 0) {
			json.put("properties", new HashMap<String, Object>());
		} else {
			Class<?> modelClass = params[0].getType();
			if (modelClass != null) {
				ApiModel apiModel = modelClass.getAnnotation(ApiModel.class);
				if (apiModel == null) {
					return null;
				}
			}
			Field[] fields = modelClass.getDeclaredFields();
			if (fields == null || fields.length == 0) {
				return null;
			}
			List<Node> nodeList = ClazzUtils.getChildrenNodes(modelClass, new HashMap<String, String>());
			log.info("nodeList:{}", JSON.toJSONString(nodeList));
			if (!CollectionUtils.isEmpty(nodeList)) {
				Set<String> allRequired = new HashSet<String>();
				Map<String, Object> result = ClazzUtils.read(nodeList, new HashMap<String, Object>(), allRequired);
				json.put("properties", result.get("properties"));
				if (!CollectionUtils.isEmpty(allRequired)) {
					json.put("required", allRequired);
				}
			}
		}
		RequestHandlerResponseVO responseVO = new RequestHandlerResponseVO();
		json.put("type", "object");
		responseVO.setReqBody(json.toJSONString());
		responseVO.setReqBodyType("json");
		List<ReqHeaders> reqHeaders = new ArrayList<ReqHeaders>();
		ReqHeaders reqHeader = new ReqHeaders();
		reqHeader.setName("Content-Type");
		reqHeader.setValue("application/json");
		reqHeaders.add(reqHeader);
		responseVO.setContentType(MediaType.APPLICATION_JSON_VALUE);
		responseVO.setMethodUri(ClazzUtils.getMethodUri(method));
		responseVO.setMethodType("POST");
		return responseVO;
	}
}
